package work.darren.itext5.generator;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import work.darren.itext.common.api.PdfGenerator;
import work.darren.itext5.event.WaterMarker;
import work.darren.itext5.event.PageMarker;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Itext5 实现HTML转PDF
 *
 * @author darren
 * @date 2019-05-25
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Itext5Generator implements PdfGenerator {


    private BaseFont baseFont;

    private static Itext5Generator instanse;

    public static PdfGenerator getInstanse() {
        if (instanse == null) {
            synchronized (Itext5Generator.class) {
                if (instanse == null) {
                    instanse = new Itext5Generator();
                    instanse.initFont();
                }
            }
        }

        return instanse;
    }

    private void initFont() {
        try {
            baseFont = BaseFont.createFont(fontpath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            throw new RuntimeException("中文字体初始化失败", e);
        }
    }


    @Override
    public void generatePdf(String html, String outputFile) throws Exception {

        Document  doc    = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputFile));

        writer.setPageEvent(new WaterMarker(baseFont));
        writer.setPageEvent(new PageMarker(baseFont));

        //设置页面边距
        doc.setMargins(40, 40, 40, 40);
        doc.open();

        XMLWorkerHelper.getInstance().parseXHtml(writer, doc, new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8, new FontProvider() {
            @Override
            public boolean isRegistered(String arg0) {
                return false;
            }

            @Override
            public Font getFont(String fontFamily, String charset, boolean arg2, float size, int style, BaseColor color) {
                return new Font(baseFont, size, style, color);
            }
        });
        doc.close();
    }
}
